import { t } from 'i18next'
import React from 'react'
import { Select } from '@kedacom/react-next'
import shallow from 'zustand/shallow'
import { StyledWrap } from './style'
import { useMtAddStore } from '../../store'
import { cascadeNodesTranslator, getCurrentMeetingMts, getSubMeetingBySmcuMtid, mtsTranslator } from '../../translator'
import { fetchCascadeNodes } from '@/api/manager/main'
import { MccCurrentMt } from '../../interface'
import { fetchAllMccMts } from '@/api/manager/main'

function CascadeSelect() {
	const { isCascade, cascadeList, currentCascadeId, mccModel, meetingMoid, smartCascadeMode, update } = useMtAddStore(
		(state) => ({
			isCascade: state.isCascade,
			cascadeList: state.cascadeList,
			currentCascadeId: state.currentCascadeId,
			mccModel: state.mccModel,
			meetingMoid: state.meetingMoid,
			smartCascadeMode: state.smartCascadeMode,
			update: state.update,
		}),
		shallow
	)
	if (!isCascade) return null
	const changeCascadeId = async (e: React.MouseEvent, id: string) => {
		update({ currentCascadeId: id })
		//本级
		if (id === '0.0.0.0_0') {
			if (mccModel) {
				let mts = mtsTranslator(getCurrentMeetingMts(mccModel))
				update({ mccCurrentMts: mts })
			}
		} else if (id === 'zn' /**智能匹配*/) {
			const list = await fetchAllMccMts(meetingMoid || '')
			if (list) {
				let _mts: MccCurrentMt[] = list.map((item) => {
					return {
						account: item.account,
						accountType: item.account_type,
						e164: item.e164,
						moid: item.moid,
					}
				})
				update({ mccCurrentMts: _mts })
			}
		} else {
			const res = await fetchCascadeNodes({ meetingMoid: meetingMoid || '', id })
			if (res) {
				let onlineSubMeetingList = mccModel ? mtsTranslator(getSubMeetingBySmcuMtid(mccModel, id)) : []
				let resDataList = cascadeNodesTranslator(res)
				update({ mccCurrentMts: [...onlineSubMeetingList, ...resDataList] })
			}
		}
	}
	return (
		<StyledWrap className="add-mt_select__i18n">
			<div className="msg">{t('会议级别')}</div>
			<div className="select-wrap">
				<Select
					width={683}
					options={cascadeList}
					value={currentCascadeId}
					valueField="id"
					labelField="name"
					onChange={changeCascadeId}
					disabled={smartCascadeMode === 1}
				></Select>
			</div>
		</StyledWrap>
	)
}
export default CascadeSelect
